package com.hit.server.comm;

import cn.hutool.core.collection.CollectionUtil;
import io.netty.channel.ChannelHandlerContext;
import lombok.extern.slf4j.Slf4j;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;


@Slf4j
public class ChannelCache {


    public static volatile Map<String, ChannelHandlerContext> channelHandlerContextMap = new ConcurrentHashMap<>();

    public static void add(ChannelHandlerContext ctx, String clientId) {
        String ip = ctx.channel().remoteAddress().toString().split(":")[0].substring(1);
        log.warn("[netty]添加通道数据 {}---{}--- {}", ip, clientId, ctx.channel().id());
        channelHandlerContextMap.put(clientId, ctx);
    }

    public static boolean isRegistered(String clientId) {
        return channelHandlerContextMap.containsKey(clientId);
    }


    public static void remove(ChannelHandlerContext ctx) {
        Iterator<Map.Entry<String, ChannelHandlerContext>> iterable = channelHandlerContextMap.entrySet().iterator();
        String clientId = null;
        while (iterable.hasNext()) {
            Map.Entry<String, ChannelHandlerContext> entry = iterable.next();
            ChannelHandlerContext channelHandlerContext = channelHandlerContextMap.get(entry.getKey());
            if (channelHandlerContext.channel().id() == ctx.channel().id()) {
                clientId = entry.getKey();
                iterable.remove();
                break;
            }
        }
        log.info("{}离线", clientId);
    }


    /**
     * 通过ChannelHandlerContext 获取 ClientId
     *
     * @param ctx
     * @return
     */
    public static String getClientIdByChannelCtx(ChannelHandlerContext ctx) {
        Map<String, String> kvPair = new HashMap<>();
        channelHandlerContextMap.forEach((clientId, channelCtx) ->
                kvPair.put(channelCtx.channel().id().asLongText(), clientId));
        return kvPair.get(ctx.channel().id().asLongText());
    }

    public static void send2All(Object object) {
        if (CollectionUtil.isNotEmpty(channelHandlerContextMap)) {
            for (String channelId : channelHandlerContextMap.keySet()) {
                ChannelHandlerContext ctx = channelHandlerContextMap.get(channelId);
                if (ctx != null) {
                    ctx.channel().writeAndFlush(object);
                }
            }
        }
    }

    public static void send2Client(String clientId, Object object) {
        ChannelHandlerContext ctx = channelHandlerContextMap.get(clientId);
        if (ctx != null) {
            ctx.channel().writeAndFlush(object);
        }
    }


}
